import 'package:get/get.dart';
import 'package:inmotion_pro/l10n/local.dart';

import '../../mixin/http_request_mixin.dart';
import 'country_model.dart';
import 'state.dart';

class AreaCodeController extends GetxController with HttpRequestMixin {
  final AreaCodeState state = AreaCodeState();

  @override
  void onInit() {
    super.onInit();
    _loadCountries();
  }

  // 加载默认国家列表（备用）
  void _loadCountries() {
    httpRequestMixinRequestAreaCodeList(
      (p0) => {
        // 将p0.$1根据国家名称首字母排序
        p0.$1.sort((a, b) => a.name.compareTo(b.name)),
        state.allCountries.assignAll(p0.$1),
        state.filteredCountries.assignAll(p0.$1),
        if (Get.arguments != null && Get.arguments is String)
          {
            state.selectedCountry.value = p0.$1.firstWhereOrNull(
              (country) => country.phoneCode == Get.arguments,
            ),
          }
      },
      showLoading: true,
      allowHttpRequest: true,
      onError: (p0) {
        
      },
    );
  }

  // 应用过滤器
  void applyFilters(CountryFilterOptions newOptions) {
    state.filterOptions.value = newOptions;

    state.filteredCountries.assignAll(state.allCountries.where((country) {
      final options = state.filterOptions.value;
      final keyword = options.keyword.toLowerCase();

      // 关键字过滤
      final matchesKeyword = keyword.isEmpty ||
          country.name.toLowerCase().contains(keyword) ||
          country.phoneCode.toLowerCase().contains(keyword) ||
          country.countryCode.contains(keyword);

      // 区域过滤
      final matchesRegion =
          options.region.isEmpty || country.name == options.region;

      return matchesKeyword && matchesRegion;
    }).toList());
  }

  // 选择国家
  void selectCountry(AreaCodeModel country) {
    state.selectedCountry.value = country;
  }

  // 获取当前选中的国家信息
  String get selectedCountryInfo {
    if (state.selectedCountry.value == null) {
      return local.no_country_selected;
    }
    final country = state.selectedCountry.value!;
    return '${country.flag} ${country.name} (${country.countryCode})';
  }
}
